<?php
/**
 * Descript: 任务
 * User: lufeng501206@gmail.com
 * Date: 2017/3/11 20:58
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Admin\Tasks;
use App\Models\ExtractCash;
use App\Models\Home\Orders;
use App\Models\Home\User;
use App\Repositories\TasksRepos;
use App\Repositories\UsersRepos;
use Illuminate\Http\Request;

class TaskController extends BaseController
{
    private $tasksRepos;
    private $usersRepos;
    private $pageLimit = 10;

    public function __construct(TasksRepos $tasksRepos, UsersRepos $usersRepos)
    {
        $this->middleware('verify.admin');
        $this->tasksRepos = $tasksRepos;
        $this->usersRepos = $usersRepos;
    }

    /**
     * 任务列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function lists()
    {
        $data['auth'] = $this->getUserAuth();
        return view('system.tasks-manager', $data);
    }

    /**
     * 任务列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function mylists(Request $request)
    {
        $account = $request->session()->get('account');
        $userId = $this->usersRepos->getAdminUserId($account);
        $data['id'] = $userId;
        $data['auth'] = $this->getUserAuth();
        return view('system.mytasks-manager', $data);
    }

    /**
     * 获取列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getLists(Request $request)
    {
        $inputs = $request->input();
        $conditions['start'] = !empty($inputs['current']) ? ($inputs['current'] - 1) * $this->pageLimit : 0;
        $conditions['limit'] = $this->pageLimit;
        if (!empty($inputs['type']) && !empty($inputs['keyword'])) {
            $conditions[$inputs['type']] = $inputs['keyword'];
        }
        if (!empty($inputs['release_userid'])) {
            $conditions['release_userid'] = $inputs['release_userid'];
        }
        $data = $this->tasksRepos->getTasksLists($conditions, false);
        $data['labels'] = config('jinbell.labels');
        $data['states'] = config('jinbell.states');
        return successJson($data);
    }

    /**
     * 新增任务
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $data['auth'] = $this->getUserAuth();
        return view('system.task-form', $data);
    }

    public function edit($id)
    {
        $conditions['id'] = $id;
        $lists = $this->tasksRepos->getTasksLists($conditions);
        if (!empty($lists)) {
            $details = $lists[0];
            $details['audit_time'] = $details['audit_time'] / 3600;
            $data['deadlime'] = $details['deadlime'];
            $data['release_time'] = $details['release_time'];
            $data['details'] = json_encode($details);
        }
        $data['id'] = $id;
        $data['auth'] = $this->getUserAuth();
        return view('system.task-form', $data);
    }

    /**
     * @param $id
     */
    public function show($id)
    {
        $conditions['id'] = $id;
        $lists = $this->tasksRepos->getTasksLists($conditions);
        $data['states'] = config('jinbell.states');
        $data['labels'] = config('jinbell.labels');
        if (!empty($lists)) {
            $data['details'] = $lists[0];
        }
        $data['auth'] = $this->getUserAuth();
        return view('system.task-detail', $data);
    }

    /**
     * 审核
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function verify(Request $request, $id)
    {
        $inputs = $request->input();
        $state = $inputs['state'];
        $taskModel = Tasks::findOrFail($id);
        // 处理发布审核中否决
        if ($taskModel->state == 3 && $state == 2) {
            $this->tasksRepos->killAllOrders($taskModel->id);
            $state = 5;
        }
        $taskModel->state = $state;
        $res = $taskModel->save();
        if ($res) {
            return successJson('', '操作成功');
        } else {
            return errorJson('', '操作失败');
        }
    }

    /**
     * 保存任务
     * @param Request $request
     * @param bool|false $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function save(Request $request, $id = false)
    {
        $data = $inputs = $request->input();

        $filerFields = ['images_arr', 'label_arr', 'used_nums', 'username', 'autho_group', 'userid', 'hours'];
        foreach ($filerFields as $key => $value) {
            if (isset($data[$value])) {
                unset($data[$value]);
            }
        }

        $data['images'] = @json_encode($data['images']);
        $validator = \Validator::make($data, [
            'title' => 'required',
            'task_desc' => 'required',
            'step_desc' => 'required',
            'images' => 'required',
            'money' => 'required',
            'label' => 'required',
            'deadlime' => 'required',
            'audit_time' => 'required',
            'release_time' => 'required',
            'number' => 'required',
        ]);
        if ($validator->fails()) {
            $errors = $validator->errors()->messages();
            $errorsMsg = "操作失败,请检查一下参数";
            //日志记录
            $resultInfo['return_msg'] = $errorsMsg;
            //返回
            return errorJson($errors, $errorsMsg);
        }

        $data['audit_time'] = $data['audit_time'] * 3600;
        if ($data['money'] <= $data['rebate']) {
            return successJson('', '推荐返利要小于佣金');
        }

        $account = $request->session()->get('account');
        $data['release_userid'] = $this->usersRepos->getAdminUserId($account);
        if (!empty($id)) {
            $res = Tasks::whereId($id)->update($data);
            if (empty($res)) {
                return successJson('', '没有修改内容');
            }
        } else {
            $data['state'] = 1;
            $res = Tasks::create($data);
        }
        if ($res) {
            return successJson('', '操作成功');
        } else {
            return errorJson();
        }
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function uploadImages(Request $request)
    {
        $file = $request->file('file');
        $relatedPath = 'tasks/' . date('Y-m-d');
        $path = $file->store($relatedPath);
        if ($path) {
            $path = env('STATIC_URL') . $path;
            return successJson($path);
        } else {
            return errorJson();
        }
    }

    /**
     * 获取好友列表
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getFriendLists()
    {
        $userInfo = $this->usersRepos->getLoginUserInfo();
        $data['lists'] = $this->usersRepos->getFriendLists($userInfo['account']);
        return successJson($data);
    }

    /**
     * 待审核任务
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function verifyTaskLists()
    {
        $data['auth'] = $this->getUserAuth();
        return view('system.verify-tasklists', $data);
    }

    /**
     * 获取待审批列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getVerifyTaskLists(Request $request)
    {
        $inputs = $request->input();
        $conditions['start'] = !empty($inputs['current']) ? ($inputs['current'] - 1) * $this->pageLimit : 0;
        $conditions['limit'] = $this->pageLimit;
        if (!empty($inputs['type']) && !empty($inputs['keyword'])) {
            $conditions[$inputs['type']] = $inputs['keyword'];
        }
        $conditions['state_arr'] = [3, 4, 5]; //审核中
        $data = $this->tasksRepos->getTasksLists($conditions, false);
        $data['labels'] = config('jinbell.labels');
        $data['states'] = config('jinbell.states');
        return successJson($data);
    }

    /**
     * 审核任务列表
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function verifyOrderLists($id)
    {
        $data['info'] = $this->tasksRepos->getTaskInfo($id);
        $data['static_url'] = env('STATIC_URL');
        $data['auth'] = $this->getUserAuth();
        return view('system.verify-orderlists', $data);
    }

    /**
     * 获取订单完成列表
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getVerifyOrderLists(Request $request, $id)
    {
        $inputs = $request->input();
        $conditions['start'] = !empty($inputs['current']) ? ($inputs['current'] - 1) * $this->pageLimit : 0;
        $conditions['limit'] = $this->pageLimit;
        $conditions['state'] = 2; //待审核
        if (!empty($inputs['type']) && !empty($inputs['keyword'])) {
            $conditions[$inputs['type']] = $inputs['keyword'];
        }
        $data = $this->tasksRepos->getOrderLists($id, $conditions);
        return successJson($data);
    }

    public function exportOrderLists(Request $request, $id)
    {
        $type = $request->input('type');
        $info = $this->tasksRepos->getTaskInfo($id);
        $appPath = app_path();
        /** Error reporting */
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        date_default_timezone_set('Europe/London');
        define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

        /** Include PHPExcel */
        require_once $appPath . '/Libraries/3rdclasses/PHPExcel/PHPExcel.php';

        // Create new PHPExcel object
        $objPHPExcel = new \PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");


        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户ID')
            ->setCellValue('B1', '用户账号')
            ->setCellValue('C1', '用户名')
            ->setCellValue('D1', '提交时间')
            ->setCellValue('D1', '提交文本')
            ->setCellValue('E1', '提交图片');

        // 设置宽度
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);

        // 渲染表格
        $maxImagesNums = 1;

        if ($type == 1) {  // 全部
            $conditions['state_arr'] = [2,4];
        } elseif ($type == 2) { //待审核
            $conditions['state_arr'] = [2];
        }
        $data = $this->tasksRepos->getOrderLists($id,$conditions,true);
        if (!empty($data) && is_array($data)) {
            $staticUrl = env('STATIC_URL');
            $row = 2;
            foreach ($data as $key => $value) {
                $imagesUrls = [];
                $images = $value['images'];
                if (!empty($images) && is_array($images)) {
                    foreach ($images as $k => $v) {
                        $imagesUrls[] = $staticUrl.$v;
                    }
                    if (count($images) > $maxImagesNums) {
                        $maxImagesNums = count($images);
                    }
                }

                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$row, $value['id'])
                    ->setCellValue('B'.$row, $value['account'])
                    ->setCellValue('C'.$row, $value['name'])
                    ->setCellValue('D'.$row, $value['order_mobile']);

                if (!empty($imagesUrls)) {
                    $col = 'E';
                    foreach ($imagesUrls as $kk => $vv) {
                        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($col)->setAutoSize(true);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.$row, $vv);
                        $objPHPExcel->getActiveSheet()->getCell($col.$row)->getHyperlink()->setUrl($vv);
                        $col ++;
                    }
                }
                $row ++ ;
            }
        }

        $imagesNums = 0;
        $col = 'E';
        while ($maxImagesNums > $imagesNums) {
            $imagesNums ++;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.'1', '图片'.$imagesNums);
            $col ++;
        }

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('任务审核资料');


        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.'【兼贝任务审核】'.$info['title'].'.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 审核用户任务
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function verifyOrder(Request $request, $id)
    {
        $inputs = $request->input();
        $state = $inputs['state'];
        $isVerifyAll = $inputs['checkboxall'];
        if ($isVerifyAll) {
            $list = $this->tasksRepos->getOrderLists($id, false, true);
        } else {
            $conditions['order_lists'] = $inputs['order_lists'];
            $list = $this->tasksRepos->getOrderLists($id, $conditions, true);
        }
        if (!empty($list)) {
            \DB::beginTransaction();
            $flag = true;
            foreach ($list as $key => $value) {
                $orderModel = Orders::FindOrFail($value['id']);

                // 必须是完成的
                if ($orderModel->state != 2) {
                    continue;
                }

                \Log::debug('开始记录任务审核操作===========================');

                \Log::debug('任务初始状态：'.$orderModel->state);
                \Log::debug('更改状态：'.$state);
                \Log::debug('$orderModel:'.$orderModel);

                $orderModel->state = $state;
                $taskDetails = $this->tasksRepos->getTaskInfo($orderModel->task_id);

                \Log::debug('$taskDetails:'.var_export($taskDetails,true));

                //入账
                if ($state == 4) {
                    $userModel = null;
                    $userModel = User::FindOrFail($orderModel->user_id);
                    if (!empty($userModel->recommend_user)) {
                        // 分提成
                        $recommendUserModel = User::where('account', $userModel->recommend_user)->first();
                        if (!empty($recommendUserModel)) {
                            $rebate = !empty($taskDetails['rebate']) ? $taskDetails['rebate'] : 0;
                            $recommendUserModel->balance += $rebate;
                            $recommendUserModel->reward_earnings += $rebate;
                            $recommendUserModel->save();
                        }
                    }

                    $userModel->balance = $userModel->balance + $taskDetails['money'];
                    $userModel->task_earnings = $userModel->task_earnings + $taskDetails['money'];
                    $userModel->save();

                    \Log::debug('当前余额:'.$userModel->balance);
                    \Log::debug('获得佣金:'.$taskDetails['money']);

                }

                \Log::debug('结束记录任务审核操作===========================');

                //触发消息
                if ($state == 3) {
                    $msgTitel = '任务审核不通过';
                } else {
                    $msgTitel = '任务审核通过';
                }

                $msgData['${mission_name}'] = $taskDetails['title'];
                $msgData['${mission_id}'] = $taskDetails['id'];
                $this->usersRepos->triggerMessage($orderModel->user_id, $msgTitel, $msgData);
                $res = $orderModel->save();
                if ($res) {
                    continue;
                } else {
                    $flag = false;
                    \DB::rollBack();
                    return errorJson();
                }
            }
            if ($flag) {
                \DB::commit();
            }
        }
        return successJson();
    }

    /**
     * 审核提现列表
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function verifyCashLists()
    {
        $data['auth'] = $this->getUserAuth();
        return view('system.verify-cashlists', $data);
    }

    /**
     * 获取提现审核列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getCashLists(Request $request)
    {
        $inputs = $request->input();
        $conditions['start'] = !empty($inputs['current']) ? ($inputs['current'] - 1) * $this->pageLimit : 0;
        $conditions['limit'] = $this->pageLimit;
        if (!empty($inputs['type']) && !empty($inputs['keyword'])) {
            $conditions[$inputs['type']] = $inputs['keyword'];
        }
        $conditions['state'] = $inputs['state'];
        $data['lists'] = $this->tasksRepos->getCashLists($conditions);
        $data['states'] = config('jinbell.cashstates');
        return successJson($data);
    }

    /**
     * 获取提现申请单页面
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function checkCashApply($id)
    {
        $data['id'] = $id;
        $data['auth'] = $this->getUserAuth();
        return view('system.check-cashapply', $data);
    }

    /**
     * 获取提现申请单信息
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function getCashApplyInfo($id)
    {
        $condition['id'] = $id;
        $res = $this->tasksRepos->getCashLists($condition);
        $data['detail'] = $res[0];
        $data['states'] = config('jinbell.cashstates');
        return successJson($data);
    }

    /**
     * 审核
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse\
     */
    public function verifyCashApply(Request $request, $id)
    {
        $data = $input = $request->input();
        $state = $data['state'];
        $cashModel = ExtractCash::FindOrFail($id);
        if ($cashModel->extract_state == 1) {
            \DB::beginTransaction();
            // 触发消息
            if ($state == 2) {
                $msgData['${cash_id}'] = $id;
                $this->usersRepos->triggerMessage($cashModel->user_id, '提现审核通过', $msgData);
            } elseif ($state == 3) {
                $msgData['${cash_id}'] = $id;
                $this->usersRepos->triggerMessage($cashModel->user_id, '提现审核不通过', $msgData);
            }
            if ($state == 2) { //通过
                $userModel = User::FindOrFail($cashModel->user_id);
                $userModel->total_earnings += $cashModel->cash_money;
                $res = $userModel->save();
                if (empty($res)) {
                    \DB::rollBack();
                    return errorJson();
                }
            }
            if ($state == 3) { //否决
                $userModel = User::FindOrFail($cashModel->user_id);
                $userModel->balance += $cashModel->cash_money;
                $res = $userModel->save();
                if (empty($res)) {
                    \DB::rollBack();
                    return errorJson();
                }
            }
            $cashModel->balance = User::FindOrFail($cashModel->user_id)->balance;
            $cashModel->extract_state = $state;
            $cashModel->handle_time = date('Y-m-d H:i:s');
            $cashModel->handle_user = $request->session()->get('account');
            $res = $cashModel->save();
            if ($res) {
                \DB::commit();
                return successJson();
            } else {
                \DB::rollBack();
                return errorJson();
            }
        } else {
            return successJson();
        }
    }
}